<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('request修改')" />
    <th:block th:include="include :: bootstrap-select-css" />
</head>
<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-request-edit">
        <input type="hidden" name="reqId" th:value="${zknjRequest.reqId}">
        <input type="hidden" name="proId" th:value="${zknjRequest.proId}">
        <h4 class="form-header h4">Request信息</h4>
        <div class="row">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-3 control-label is-required">名称：</label>
                    <div class="col-sm-8">
                        <input id="reqName" name="reqName" class="form-control" type="text" th:value="${zknjRequest.reqName}" required>
                    </div>
                </div>
            </div>
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-3 control-label">描述：</label>
                    <div class="col-sm-8">
                        <input name="reqDes" class="form-control" type="text" th:value="${zknjRequest.reqDes}">
                    </div>
                </div>
            </div>
        </div>

        <h4 class="form-header h4">Sample信息</h4>
        <div class="row">
            <div class="col-sm-12">
                <button type="button" class="btn btn-success btn-sm" onclick="addRow()"><i class="fa fa-plus"> 增加</i></button>
                <button type="button" class="btn btn-danger btn-sm" onclick="sub.delRow()"><i class="fa fa-minus"> 删除</i></button>
                <div class="col-sm-12 select-table table-striped">
                    <table id="bootstrap-table"></table>
                </div>
            </div>
        </div>
    </form>
    <!-- Edit弹窗-->
    <div class="modal inmodal fade" id="sampleModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
                    </button>
                    <h4 class="modal-title">Edit Sample</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal m" id="form-sample">
                        <h4 class="form-header h4">样品信息</h4>
                        <input type="hidden" id="inp-index">
                        <div class="form-group">
                            <label class="col-sm-3 control-label is-required">名称：</label>
                            <div class="col-sm-8">
                                <input id="samName" name="samName" class="form-control" type="text" required>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label is-required">Slot：</label>
                            <div class="col-sm-8">
                                <input id="samSlot" name="samSlot" class="form-control" type="number" min="1" max="999" required>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label">描述：</label>
                            <div class="col-sm-8">
                                <input id="samDes" name="samDes" class="form-control" type="text">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label">质量：</label>
                            <div class="col-sm-8">
                                <input id="quantity" name="quantity" class="form-control" type="text">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label">分子式：</label>
                            <div class="col-sm-8">
                                <input id="mFormula" name="mFormula" class="form-control" type="text">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label">分子量：</label>
                            <div class="col-sm-8">
                                <input id="mWeight" name="mWeight" class="form-control" type="text">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label is-required">溶剂：</label>
                            <div class="col-sm-8">
                                <select class="form-control selectpicker" id="solvent" name="solvent" required>
                                    <option th:each="solvent:${solvents}" th:value="${solvent.solventName}" th:text="${solvent.solventName}" ></option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label">优先：</label>
                            <div class="col-sm-8">
                                <label class="toggle-switch switch-solid">
                                    <input type="checkbox" id="priority">
                                    <span></span>
                                </label>
                            </div>
                        </div>
                        <h4 class="form-header h4">服务选择</h4>
                        <div class="form-group">
                            <label class="col-sm-3 control-label is-required">请选择仪器：</label>
                            <div class="col-sm-8">
                                <select class="form-control selectpicker" id="sel-inst" data-none-selected-text="请选择仪器" onchange="selectInstrument()">
                                    <option th:each="inst:${instruments}" th:data-subtext="${inst.hostId}" th:value="${inst.instId}" th:text="${inst.instName}"></option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label is-required">请选择服务：</label>
                            <div class="col-sm-8">
                                <select class="form-control selectpicker" id="sel-services" data-none-selected-text="请选择服务(可多选)" onchange="selectServices()" multiple>
                                    <option th:each="service:${services}" th:data="${service.instId}" th:class="'inst-'+${service.instId}" th:value="${service.serId}+','+${service.serName}" th:text="${service.serName}" th:disabled="${service.userPermissionFlag == false}"></option>
                                </select>
                            </div>
                        </div>
                    </form>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>
                    <button id="saveSam" type="button" class="btn btn-primary">保存</button>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="row" style="padding-top: 10px">
    <div class="col-sm-offset-5 col-sm-10">
        <button type="button" class="btn btn-sm btn-primary" onclick="submitHandler()"><i class="fa fa-check"></i>保 存</button>&nbsp;
        <button type="button" class="btn btn-sm btn-danger" onclick="closeItem()"><i class="fa fa-reply-all"></i>关 闭 </button>
    </div>
</div>
<th:block th:include="include :: footer" />
<th:block th:include="include :: bootstrap-select-js" />
<script th:inline="javascript">
    var editFlag = [[${@permission.hasPermi('system:request:edit')}]];
    var removeFlag = [[${@permission.hasPermi('system:request:remove')}]];
    var yesnoStatusDatas = [[${@dict.getType('sys_yn_status')}]];
    var reqId = [[${zknjRequest.reqId}]];
    var sams = [[${zknjRequest.samples}]];
    var prefix = ctx + "system/request2";

    /* modal层无法选中的解决方案， 第二方案：将modal层放在body外*/
    $("#sampleModal").prependTo("body");

    function getData(params) {
        var data = [];
        $.each(params, function(index, v){
            v.index = index;
            data.push(v);
        })
        return data;
    }

    $(function() {
        var options = {
            data: getData(sams),
            modalName: "服务",
            pagination: false,
            showSearch: false,
            showRefresh: false,
            showToggle: false,
            showColumns: false,
            sidePagination: "client",
            columns: [{
                checkbox: true
            },
                {
                    field: 'samId',
                    title: 'id',
                    visible: false,
                },
                {
                    field: 'samName',
                    title: '样品名称',
                },
                {
                    field: 'samSlot',
                    title: 'slot',
                    align: 'center'
                },
                {
                    field: 'samDes',
                    title: '描述'
                },
                {
                    field: 'instName',
                    title: '仪器',
                    formatter: function (value, row, index) {
                        return  row.services[0].instrument.instName;
                    }
                },
                {
                    field: 'solvent',
                    title: '溶剂'
                },
                {
                    field: 'priority',
                    title: '优先',
                    formatter: function(value, row, index) {
                        return $.table.selectDictLabel(yesnoStatusDatas, value);
                    }
                },
                {
                    field: 'services',
                    title: '服务',
                    formatter: function (value, row, index) {
                        var services = [];
                        $.each(value,function (index, data) {
                            var s = JSON.stringify(data);
                            var parse = JSON.parse(s);
                            services.push('<a href="javascript:;"><i class="fa fa-adjust fa-lg"></i> '+parse.serName+'</a><br>')
                        })
                        return services.join('');
                    }
                },
                {
                    field: 'methods',
                    title: '方法',
                    formatter: function (value, row, index) {
                        var methods = [];
                        $.each(value,function (index, data) {
                            var s = JSON.stringify(data);
                            var parse = JSON.parse(s);
                            methods.push('<a href="javascript:;" ><i class="fa fa-adjust fa-lg"></i> '+parse.modName+'</a><br>')
                        })
                        return methods.join('');
                    }
                },
                {
                    field: 'quantity',
                    title: '样品量'
                },
                {
                    field: 'mFormula',
                    title: '分子式'
                },
                {
                    field: 'mWeight',
                    title: '分子量'
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function(value, row, index) {
                        var actions = [];
                        var edit = '<a class="btn btn-success btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="editSample(\'' + index + '\')"><i class="fa fa-edit"></i>编辑</a> ';
                        actions.push(edit);
                        return actions.join('');
                    }
                }
            ]
        };
        $.table.init(options);
    });

    /* Edit Sample界面*/
    function editSample(index) {
        $("#inp-index").val(index);
        var data = $("#" + table.options.id).bootstrapTable('getData');
        // console.log(data[index]);
        var row = data[index];
        var ids = [];
        $.each(row.services, function(k, v) {
            ids.push(v.serId+","+v.serName);
        })
        //赋值instrument、services
        $("#sel-services").selectpicker('val', ids).trigger("change");
        $('#sel-services').selectpicker('refresh');
        var inst = $('#sel-services').find("option:selected").attr('data');
        $('#sel-services').find("option").hide();
        $('.inst-'+inst).show();
        $('#sel-services').selectpicker('refresh');
        $("#sel-inst").selectpicker('val', inst);
        $('#sel-inst').selectpicker('refresh');
        $("#samName").val(row.samName);
        $("#samSlot").val(row.samSlot);
        $("#samDes").val(row.samDes);
        $("#quantity").val(row.quantity);
        $("#mFormula").val(row.mFormula);
        $("#mWeight").val(row.mWeight);
        $("#solvent").val(row.solvent);
        $("#priority").val(row.priority);
        //是否优先
        if(row.priority == 1){
            $("#priority").prop("checked",true);
        }
        //弹框
        $("#sampleModal").modal('show');
        $.each(row.services, function(k, v) {
            $.each(row.methods, function(k2, v2) {
                if(v2.serId == v.serId) {
                    $("#method_"+v2.serId).find("option[value='"+v2.modId+"']").attr("selected", true);
                }
            })

        })
    }

    /* 主子表-提交 */
    function submitHandler(index, layero){
        if ($("#form-request-edit").validate().form()) {
            var data = $("#form-request-edit").serializeArray();
            var dataColumns = [];
            for (var columnIndex = 0; columnIndex < table.options.columns.length; columnIndex++) {
                // if (table.options.columns[columnIndex].visible != false) {
                //
                // }
                dataColumns.push(table.options.columns[columnIndex]);
            }
            var data2 = $("#" + table.options.id).bootstrapTable('getData');
            var count = data2.length;
            var samNames = [];
            for (var dataIndex = 0; dataIndex < count; dataIndex++) {
                var columns = $('#' + table.options.id + ' tr[data-index="' + dataIndex + '"] td:visible');
                var value = data2[dataIndex];
                // console.log(value);
                for (var i = 0; i < columns.length; i++) {
                    var key = dataColumns[i].field;
                    if (key == "index" || key == null) {
                        // console.log("index");
                    }else if(key == "services"){
                        var element = value[key];
                        var serIds = [];
                        $.each(element, function (k, v) {
                            serIds.push(v.serId);
                        })
                        data.push({"name": "samples[" + dataIndex + "].serIds", "value": serIds.join(",")});
                    }else if(key == "methods"){
                        var element = value[key];
                        var modIds = [];
                        $.each(element, function (k, v) {
                            modIds.push(v.modId);
                        })
                        data.push({"name": "samples[" + dataIndex + "].modIds", "value": modIds.join(",")});
                    }else {
                        if(key == "samName"){
                            if(samNames!=null && samNames.includes(value[key].trim())){
                                $.modal.alertError("请使用不同的样品名称");
                                return;
                            }else {
                                samNames.push(value[key].trim());
                            }
                        }
                        data.push({"name":"samples[" + dataIndex + "]." + key, "value": value[key]});
                    }
                }
            }
            // alert(JSON.stringify(data));
            $.operate.saveTab(prefix + "/edit", data);
        }
    }

    /* Edit Sample 点击保存事件*/
    $("#saveSam").on("click",function () {
        var index = $("#inp-index").val();
        var sample;
        if ($('#form-sample').validate().form()) {
            //服务判空
            var services = $('#sel-services').val();
            if($.common.isEmpty(services)){
                $.modal.alertError("服务不能为空");
                return false;
            }
            var sample = $('#form-sample').serializeArray();
            var priority = $("input[id='priority']").is(':checked') == true ? 1 : 0;
            sample.push({"name": "priority", "value": priority});
        }
        if(sample == null){
            return false;
        }
        var modIds = [];
        $.each(sample, function (index, value) {
            if(sample[index].name.startsWith("method")){
                modIds.push(sample[index].value)
            }
        })
        var config = {
            url: prefix + "/getServices",
            type: "post",
            dataType: "json",
            data: {"modIds": modIds.toString()},
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍候...");
            },
            success: function(result) {
                //回调事件
                $("#" + table.options.id).bootstrapTable("updateRow", {
                    index: index,
                    row: {
                        samName: sample[0].value,
                        samSlot: sample[1].value,
                        samDes: sample[2].value,
                        instName: "",
                        solvent: sample[6].value,
                        priority: sample[sample.length - 1].value,
                        services: result.data.services,
                        methods: result.data.methods,
                        quantity: sample[3].value,
                        mFormula: sample[4].value,
                        mWeight: sample[5].value,
                    }
                })
                $.modal.closeLoading();
            }
        };
        $.ajax(config);
        $("#sampleModal").modal('hide');
        $.form.reset('form-sample');
    })

    /* Add Sample*/
    function addRow() {
        var options = {
            title: 'Add Sample',
            url: prefix + "/addSam/"+reqId,
            callBack: doSubmit
        };
        $.modal.openOptions(options);

        function doSubmit(index, layero){
            var sample = layero.find("iframe")[0].contentWindow.getSample();
            // console.log(sample);
            if(sample == null){
                return false;
            }
            //获取选择的方法id集合
            var modIds = [];
            $.each(sample, function (index, value) {
                if(sample[index].name.startsWith("method")){
                    modIds.push(sample[index].value)
                }
            })
            var config = {
                url: prefix + "/getServices",
                type: "post",
                dataType: "json",
                data: {"modIds": modIds.toString()},
                beforeSend: function () {
                    $.modal.loading("正在处理中，请稍候...");
                },
                success: function(result) {
                    //回调事件
                    var count = $("#" + table.options.id).bootstrapTable('getData').length;
                    var row = {
                        index: $.table.serialNumber(count),
                        samName: sample[0].value,
                        samSlot: sample[1].value,
                        samDes: sample[2].value,
                        instName: "",
                        solvent: sample[6].value,
                        priority: sample[sample.length-1].value,
                        services: result.data.services,
                        methods: result.data.methods,
                        quantity: sample[3].value,
                        mFormula: sample[4].value,
                        mWeight: sample[5].value,
                    }
                    sub.addRow(row);
                    $.modal.closeLoading();
                }
            };
            $.ajax(config)
            $.modal.close(index);
        }
    }

    /* 选择仪器*/
    function selectInstrument(){
        $('#sel-services').find("option").hide();
        var instId = $('#sel-inst').val();
        $('.inst-'+instId).show();
        $("#sel-services").selectpicker('val', '').trigger("change");
        $('#sel-services').selectpicker('refresh');
    }

    /* 选择服务*/
    function selectServices(){
        var values = $('#sel-services').val();
        $(".method").remove();
        $.each(values, function (index, value){
            var split = value.split(',');
            var method = [];
            var config = {
                url: prefix + "/getMethods",
                type: "post",
                dataType: "json",
                data: {"serId": split[0]},
                async: false,       // 同步
                beforeSend: function () {
                    $.modal.loading("正在处理中，请稍候...");
                },
                success: function(result) {
                    //回调事件
                    $.each(result.data, function (index, value) {
                        var option = '<option value="' + value.modId + '">' + value.modName + '</option>';
                        method.push(option);
                    })
                    var group = '<div class="form-group method"><label class="col-sm-3 control-label is-required">'+split[1]+'方法：</label>' +
                        '<div class="col-sm-8"><select class="form-control" id="method_'+split[0]+'" name="method['+index+']" required>'+method.join("")+'</select></div></div>';
                    $('#form-sample').append(group);
                    $.modal.closeLoading();
                }
            };
            $.ajax(config)
        })
    }
</script>
</body>
</html>